package com.hafu.dao;
import com.hafu.model.KuCun;
import com.hafu.model.RuKuDetail;
import com.hafu.util.DbUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public class KuCunDao{
    public ArrayList<KuCun>getKuCunList() throws SQLException {
        ArrayList<KuCun> List = new ArrayList<>();
        Connection conn = DbUtil.getConn();
        String sql = "select * from kucun";
        try {
            PreparedStatement preparedStatement = conn.prepareStatement(sql);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String spName = resultSet.getString("spname");
                int num = resultSet.getInt("num");
                KuCun kuCun1 = new KuCun(id, spName, num);
                List.add(kuCun1);}
        }catch(SQLException throwables){
            throwables.printStackTrace();
        }
        return List;
    }
    public KuCun getKuCunBySpName(String spName, Connection conn) throws SQLException{
        String sql = "select * from kucun where spname=?";
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        preparedStatement.setString(1, spName);
        ResultSet resultSet = preparedStatement.executeQuery();
        if (resultSet.next()){
            int id = resultSet.getInt("id");
            String name = resultSet.getString("spname");
            int num = resultSet.getInt("num");
            KuCun kuCun = new KuCun(id, spName, num);
            return kuCun;
        }
        return null;
    }

    public boolean addKuCun(KuCun kuCun, Connection conn) throws SQLException{
        String sql = "insert into kucun(spname,num) values(?,?)";
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        preparedStatement.setString(1, kuCun.getSpName());
        preparedStatement.setInt(2, kuCun.getNum());
        int i = preparedStatement.executeUpdate();
        if (i>0){
            return true;
        } else return false;
    }

    public boolean updateKuCun(KuCun kuCunBySpName, Connection conn)throws SQLException {
        String sql = "update kucun set num=? where spname=?";
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        preparedStatement.setInt(1, kuCunBySpName.getNum());
        preparedStatement.setString(2, kuCunBySpName.getSpName());
        int i = preparedStatement.executeUpdate();
        if (i>0){
            return true;
        } else return false;
    }
}







